<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  BarChart,
  CanvasRenderer,
  DataZoomComponent
])

interface ChartDataInterface {
  months: string[];
  revenue: number[];
  cost: number[];
  profit: number[];
  comparisonRevenue?: number[];
  comparisonCost?: number[];
  comparisonProfit?: number[];
}

const props = defineProps({
  chartData: {
    type: Object as () => ChartDataInterface,
    required: true
  },
  chartType: {
    type: String,
    default: 'mixed'
  },
  enableComparison: {
    type: Boolean,
    default: true
  }
})

const chartContainer = ref(null)
let chart: echarts.ECharts | null = null

const getChartOption = () => {
  const { months, revenue, cost, profit, comparisonRevenue, comparisonCost, comparisonProfit } = props.chartData
  const { chartType, enableComparison } = props
  
  // 基础配置
  const option: any = {
    title: {
      text: '利润趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      },
      show: false
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#e6e6e6',
      borderWidth: 1,
      textStyle: {
        color: '#333'
      },
      formatter: function(params: any) {
        let res = params[0].axisValue + '<br/>'
        params.forEach((item: any) => {
          let colorSpan = `<span style="display:inline-block;width:10px;height:10px;background:${item.color};border-radius:50%;margin-right:8px;"></span>`
          
          // 判断是否是对比数据
          const isComparison = item.seriesName.includes('同期')
          const valueStyle = isComparison ? 'opacity:0.8;font-weight:normal;' : 'font-weight:bold;'
          
          res += `<div style="display:flex;align-items:center;margin:5px 0;">
                   ${colorSpan}
                   <span>${item.seriesName}: </span>
                   <span style="${valueStyle}margin-left:5px">¥ ${item.value.toLocaleString()}</span>
                 </div>`
        })
        return res
      }
    },
    legend: {
      data: ['营业收入', '营业成本', '净利润'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '8%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisLabel: {
        formatter: (value: number) => {
          if (value >= 10000) {
            return (value / 10000) + 'w'
          }
          return value
        }
      },
      splitLine: {
        lineStyle: {
          color: '#eee',
          type: 'dashed'
        }
      }
    },
    series: []
  }
  
  // 根据图表类型配置系列
  if (chartType === 'bar') {
    // 柱状图
    option.series = [
      {
        name: '营业收入',
        type: 'bar',
        data: revenue,
        barWidth: 12,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67C23A' },
            { offset: 1, color: '#95D475' }
          ])
        }
      },
      {
        name: '营业成本',
        type: 'bar',
        data: cost,
        barWidth: 12,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#F56C6C' },
            { offset: 1, color: '#F89898' }
          ])
        }
      },
      {
        name: '净利润',
        type: 'bar',
        data: profit,
        barWidth: 12,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#409EFF' },
            { offset: 1, color: '#79BBFF' }
          ])
        }
      }
    ]
    
    // 如果启用了对比
    if (enableComparison && comparisonRevenue && comparisonCost && comparisonProfit) {
      option.legend.data = ['营业收入', '营业成本', '净利润', '同期收入', '同期成本', '同期利润']
      
      option.series.push(
        {
          name: '同期收入',
          type: 'bar',
          data: comparisonRevenue,
          barWidth: 12,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(103, 194, 58, 0.5)' },
              { offset: 1, color: 'rgba(149, 212, 117, 0.5)' }
            ])
          },
          barGap: '0%'
        },
        {
          name: '同期成本',
          type: 'bar',
          data: comparisonCost,
          barWidth: 12,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(245, 108, 108, 0.5)' },
              { offset: 1, color: 'rgba(248, 152, 152, 0.5)' }
            ])
          },
          barGap: '0%'
        },
        {
          name: '同期利润',
          type: 'bar',
          data: comparisonProfit,
          barWidth: 12,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
              { offset: 1, color: 'rgba(121, 187, 255, 0.5)' }
            ])
          },
          barGap: '0%'
        }
      )
    }
  } else if (chartType === 'line') {
    // 折线图
    option.series = [
      {
        name: '营业收入',
        type: 'line',
        data: revenue,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#67C23A'
        },
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '营业成本',
        type: 'line',
        data: cost,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#F56C6C'
        },
        itemStyle: {
          color: '#F56C6C'
        }
      },
      {
        name: '净利润',
        type: 'line',
        data: profit,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
    
    // 如果启用了对比
    if (enableComparison && comparisonRevenue && comparisonCost && comparisonProfit) {
      option.legend.data = ['营业收入', '营业成本', '净利润', '同期收入', '同期成本', '同期利润']
      
      option.series.push(
        {
          name: '同期收入',
          type: 'line',
          data: comparisonRevenue,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 2,
            color: '#67C23A',
            type: 'dashed'
          },
          itemStyle: {
            color: '#67C23A'
          },
          opacity: 0.6
        },
        {
          name: '同期成本',
          type: 'line',
          data: comparisonCost,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 2,
            color: '#F56C6C',
            type: 'dashed'
          },
          itemStyle: {
            color: '#F56C6C'
          },
          opacity: 0.6
        },
        {
          name: '同期利润',
          type: 'line',
          data: comparisonProfit,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 2,
            color: '#409EFF',
            type: 'dashed'
          },
          itemStyle: {
            color: '#409EFF'
          },
          opacity: 0.6
        }
      )
    }
  } else {
    // 混合图 - 收入成本柱状，利润为线
    option.series = [
      {
        name: '营业收入',
        type: 'bar',
        data: revenue,
        barWidth: 12,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#67C23A' },
            { offset: 1, color: '#95D475' }
          ])
        }
      },
      {
        name: '营业成本',
        type: 'bar',
        data: cost,
        barWidth: 12,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#F56C6C' },
            { offset: 1, color: '#F89898' }
          ])
        }
      },
      {
        name: '净利润',
        type: 'line',
        data: profit,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        itemStyle: {
          color: '#409EFF'
        },
        emphasis: {
          focus: 'series'
        },
        z: 10
      }
    ]
    
    // 如果启用了对比
    if (enableComparison && comparisonRevenue && comparisonCost && comparisonProfit) {
      option.legend.data = ['营业收入', '营业成本', '净利润', '同期收入', '同期成本', '同期利润']
      
      option.series.push(
        {
          name: '同期收入',
          type: 'bar',
          data: comparisonRevenue,
          barWidth: 12,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(103, 194, 58, 0.5)' },
              { offset: 1, color: 'rgba(149, 212, 117, 0.5)' }
            ])
          },
          barGap: '0%'
        },
        {
          name: '同期成本',
          type: 'bar',
          data: comparisonCost,
          barWidth: 12,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(245, 108, 108, 0.5)' },
              { offset: 1, color: 'rgba(248, 152, 152, 0.5)' }
            ])
          },
          barGap: '0%'
        },
        {
          name: '同期利润',
          type: 'line',
          data: comparisonProfit,
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            width: 2,
            color: '#409EFF',
            type: 'dashed'
          },
          itemStyle: {
            color: '#409EFF'
          },
          emphasis: {
            focus: 'series'
          },
          opacity: 0.6,
          z: 9
        }
      )
    }
  }
  
  return option
}

const initChart = () => {
  if (!chartContainer.value) return
  
  chart = echarts.init(chartContainer.value)
  const option = getChartOption()
  
  chart.setOption(option)
  
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  chart && chart.resize()
}

const updateChart = () => {
  if (!chart) return
  
  const option = getChartOption()
  chart.setOption(option)
}

watch(() => props.chartType, () => {
  nextTick(updateChart)
})

watch(() => props.chartData, () => {
  nextTick(updateChart)
}, { deep: true })

watch(() => props.enableComparison, () => {
  nextTick(updateChart)
})

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 组件销毁时清理chart
defineExpose({
  dispose: () => {
    if (chart) {
      chart.dispose()
      chart = null
    }
    window.removeEventListener('resize', handleResize)
  }
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style> 